/* eslint-disable array-callback-return */
import React from 'react';
import { connect } from 'dva';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import HOCSelect from '@/components/AntDesign/Select';
import {
  Col,
  Row,
  Radio,
  Input,
  InputNumber,
  Select,
  message,
  Modal,
  Spin,
  AutoComplete,
} from 'antd';

const { Option } = Select;
const FormItem = Form.Item;
const RadioGroup = Radio.Group;
const { Search } = Input;
@connect(({ busicont, loading }) => ({
  loading: loading.models.busicont || loading.models.publicdata,
  busicont,
}))
@Form.create()
class SupplyAddModal extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      modalVisible: false,
      comTypeList: [],
      industryCodeList: [],
      surplus: 1,
      Customering: 1, // 默认的客户选中值
      baicustList: [],
      custlistData: [],
      modeName: '',
      cityList: 1,
      existing: [],
    };
  }

  componentDidMount() {
    const { dispatch, displayb, existing } = this.props;
    dispatch({
      type: 'publicdata/fetchDictCode',
      payload: ['CORP_NATURE', 'INDST_CODE'],
    }).then(data => {
      this.setState({
        modalVisible: displayb,
        comTypeList: data.CORP_NATURE,
        industryCodeList: data.INDST_CODE,
        existing,
      });
    });
  }

  // 切换客户
  CustomerMesge = e => {
    const { form } = this.props;
    const getFieldsList = form.getFieldsValue();
    Object.keys(getFieldsList).forEach(key => {
      if (
        key === 'name' ||
        key === 'nameone' ||
        key === 'nametwo' ||
        key === 'no' ||
        key === 'corpNature' ||
        key === 'uniCreditCode' ||
        key === 'industryCode'
      ) {
        form.setFieldsValue({ [key]: '' });
      }
    });
    this.setState({
      Customering: e.target.value,
    });
  };

  // 已有客户的客户搜索
  search = value => {
    const { dispatch } = this.props;
    if (value.trim().length) {
      this.setState({ baicustList: [], fetching: true });
      dispatch({
        type: 'busicont/getCustName',
        payload: {
          name: value,
        },
      }).then(response => {
        if (response.success && response.data.length) {
          this.setState({ baicustList: response.data, fetching: false });
        }
      });
    } else {
      this.setState({ baicustList: [], fetching: false });
    }
  };

  // 新增客户的客户名称搜索
  searchCust = value => {
    const { dispatch } = this.props;
    dispatch({
      type: 'busicont/getAddCustSearch',
      payload: {
        name: value,
      },
    }).then(response => {
      if (response.success && response.data) {
        this.setState({
          custlistData: response.data,
        });
      } else {
        this.setState({ custlistData: [] });
      }
    });
  };

  // 选择某一客户
  selectCust = custId => {
    const { form } = this.props;
    const { custlistData } = this.state;
    let custInfo = null;
    custlistData.map(item => {
      if (custId === item.mdCustId) {
        custInfo = item;
      }
    });
    this.setState({
      modeName: custInfo.name,
    });
    // 选择某一客户带出统一社会信用代码，公司性质，行业分类
    const getFieldsList = form.getFieldsValue();
    Object.keys(getFieldsList).forEach(key => {
      if (custInfo[key]) {
        if (key === 'corpNature' || key === 'industryCode') {
          form.setFieldsValue({ [key]: { key: `${custInfo[key]}`, mdCustId: null } });
        } else {
          form.setFieldsValue({ [key]: custInfo[key], mdCustId: null });
        }
      }
    });
  };

  // 获取输入的客户名称
  getInputCustName = e => {
    const { form } = this.props;
    form.setFieldsValue({ nametwo: e });
    this.setState({
      modeName: e,
    });
  };

  // 统一社会信用代码搜索
  searchCusttwo = value => {
    const { dispatch, form } = this.props;
    dispatch({
      type: 'busicont/getmdCustInfo',
      payload: {
        uniCreditCode: value,
      },
    }).then(response => {
      if (response.success && response.data) {
        // 统一社会信用代码带出客户名称，公司性质，行业分类
        const getFieldsList = form.getFieldsValue();
        Object.keys(getFieldsList).forEach(key => {
          if (response.data[key]) {
            if (key === 'corpNature' || key === 'industryCode') {
              form.setFieldsValue({
                [key]: { key: `${response.data[key]}`, mdCustId: null },
              });
              form.setFieldsValue({ no: null });
            } else {
              this.setState({
                modeName: response.data.name,
              });
              form.setFieldsValue({ nametwo: response.data.name, no: null });
            }
          }
        });
      }
    });
  };

  modalBlock = flag => {
    const { getCustNametwo } = this.props;
    getCustNametwo(false);
    this.setState({
      surplus: 1,
      modalVisible: !!flag,
    });
  };

  // 提交数据
  submit = () => {
    const { dispatch, form, custListadfa } = this.props;
    const { Customering, cityList, existing, modeName } = this.state;
    const getFieldsList = form.getFieldsValue();
    form.validateFieldsAndScroll(err => {
      if (!err) {
        if (
          getFieldsList.nameone ||
          getFieldsList.nametwo ||
          getFieldsList.no ||
          getFieldsList.corpNature ||
          getFieldsList.uniCreditCode ||
          getFieldsList.industryCode
        ) {
          if (Customering === 1) {
            const arr = getFieldsList.nameone;
            arr.map(item => {
              const obiList = { custId: item.split('&')[0], custName: item.split('&')[1] };
              const custList = [];
              if (cityList === 1) {
                this.setState({
                  cityList: 2,
                });
                custList.push(obiList);
                custListadfa(custList);
              } else {
                existing.map(items => {
                  if (items.custId === obiList.custId) {
                    message.warning('不可添加重复客户');
                  } else {
                    existing.push(obiList);
                    const newArr = [];
                    for (let i = 0; i < existing.length; i += 1) {
                      let flag = true;
                      for (let j = 0; j < newArr.length; j += 1) {
                        if (existing[i].custId === newArr[j].custId) {
                          flag = false;
                        }
                      }
                      if (flag) {
                        newArr.push(existing[i]);
                      }
                    }
                    custListadfa(newArr);
                  }
                });
              }
            });
            this.modalBlock(false);
          } else {
            const parmer = {
              name: modeName,
              no: getFieldsList.no,
              corpNature: getFieldsList.corpNature.key,
              uniCreditCode: getFieldsList.uniCreditCode,
              industryCode: getFieldsList.industryCode.key,
            };
            dispatch({
              type: 'busicont/supplyInsert',
              payload: parmer,
            }).then(response => {
              if (response.success && response.data) {
                const custList = [];
                const addcuname = { custId: response.data.custId, custName: response.data.name };
                custList.push(addcuname);
                custListadfa(custList);
                this.modalBlock(false);
              } else {
                message.warning(`${response.message}`);
              }
            });
          }
        }
      }
    });
  };

  // 渲染函数
  render() {
    const {
      modalVisible,
      baicustList,
      fetching,
      custlistData,
      comTypeList,
      industryCodeList,
      surplus,
      Customering,
    } = this.state;
    const {
      loading,
      form: { getFieldDecorator },
    } = this.props;
    // 模态框配置
    const modalConfig = {
      width: 560,
      title: '关联客户',
      visible: modalVisible,
      confirmLoading: loading,
      onOk: this.submit,
      okText: '确定',
      onCancel: () => {
        this.modalBlock(false);
        this.setState({ surplus: 0 });
      },
    };
    const options = custlistData.map(opt => (
      <Option key={opt.mdCustId} value={opt.mdCustId}>
        {opt.name}
      </Option>
    ));
    // 公司类型
    const comTypeOL = comTypeList.map(option => (
      <Option key={option.itemCode}>{option.itemName}</Option>
    ));
    // 行业分类
    const industryCodeOL = industryCodeList.map(option => (
      <Option key={option.itemCode}>{option.itemName}</Option>
    ));
    return (
      <Spin tip="Loading..." spinning={loading}>
        {surplus === 1 ? (
          <Modal {...modalConfig}>
            <Form layout="horizontal">
              <FormItem style={{ marginLeft: '35%' }}>
                <RadioGroup onChange={this.CustomerMesge} value={Customering}>
                  <Radio value={1}>已有客户</Radio>
                  <Radio value={2}>新增客户</Radio>
                </RadioGroup>
              </FormItem>
              {Customering === 1 ? (
                <Row>
                  <Col>
                    <FormItem label="客户" labelCol={{ span: 8 }} wrapperCol={{ span: 13 }}>
                      {getFieldDecorator('nameone', {
                        rules: [{ required: true, message: '请选择' }],
                      })(
                        <HOCSelect
                          placeholder="请输入关键字检索，可复选"
                          mode="multiple"
                          showSearch
                          showArrow={false}
                          filterOption={false}
                          onSearch={this.search}
                          notFoundContent={fetching ? <Spin size="small" /> : null}
                        >
                          {baicustList.map(item => (
                            <Option key={`${item.custId}&${item.name}`}>{item.name}</Option>
                          ))}
                        </HOCSelect>
                      )}
                    </FormItem>
                  </Col>
                </Row>
              ) : (
                <Row>
                  <Col>
                    <FormItem label="客户名称" labelCol={{ span: 8 }} wrapperCol={{ span: 13 }}>
                      {getFieldDecorator('nametwo', {
                        rules: [{ required: true, message: '请输入' }],
                      })(
                        <AutoComplete
                          dataSource={options}
                          onSelect={this.selectCust}
                          onChange={this.getInputCustName}
                        >
                          <Search
                            placeholder="请输入关键字检索"
                            maxLength={100}
                            onSearch={value => this.searchCust(value)}
                          />
                        </AutoComplete>
                      )}
                    </FormItem>
                  </Col>
                  <Col>
                    <FormItem
                      label="统一社会信用代码"
                      labelCol={{ span: 8 }}
                      wrapperCol={{ span: 13 }}
                    >
                      {getFieldDecorator('uniCreditCode', {
                        rules: [
                          {
                            required: true,
                            message: '18位的数字与字母组合',
                            pattern: /^[A-Za-z0-9]{18}$/,
                          },
                        ],
                      })(
                        <AutoComplete>
                          <Search
                            placeholder="请输入关键字检索"
                            maxLength={100}
                            onSearch={value => this.searchCusttwo(value)}
                          />
                        </AutoComplete>
                      )}
                    </FormItem>
                  </Col>
                  <Col>
                    <FormItem label="客户编号" labelCol={{ span: 8 }} wrapperCol={{ span: 13 }}>
                      {getFieldDecorator('no', {
                        rules: [{ required: true, message: '请输入不超过15位的纯数字' }],
                      })(
                        <InputNumber
                          min={1}
                          maxLength={15}
                          placeholder="请输入纯数字"
                          style={{ width: '100%' }}
                        />
                      )}
                    </FormItem>
                  </Col>
                  <Col>
                    <FormItem label="公司类型" labelCol={{ span: 8 }} wrapperCol={{ span: 13 }}>
                      {getFieldDecorator('corpNature', {
                        rules: [{ required: true, message: '请选择' }],
                      })(
                        <HOCSelect
                          placeholder="请输入关键字检索"
                          style={{ width: '100%' }}
                          allowClear
                          labelInValue
                          showSearch
                          optionFilterProp="children"
                        >
                          {comTypeOL}
                        </HOCSelect>
                      )}
                    </FormItem>
                  </Col>
                  <Col>
                    <FormItem label="行业分类" labelCol={{ span: 8 }} wrapperCol={{ span: 13 }}>
                      {getFieldDecorator('industryCode', {
                        rules: [{ required: true, message: '请选择' }],
                      })(
                        <HOCSelect
                          placeholder="请输入关键字检索"
                          style={{ width: '100%' }}
                          allowClear
                          labelInValue
                          showSearch
                          optionFilterProp="children"
                        >
                          {industryCodeOL}
                        </HOCSelect>
                      )}
                    </FormItem>
                  </Col>
                </Row>
              )}
            </Form>
          </Modal>
        ) : null}
      </Spin>
    );
  }
}
export default SupplyAddModal;
